package cn.scw.common.separate;

import cn.scw.common.separate.common.Constants;
import cn.scw.common.separate.model.BindAppIdModel;
import cn.scw.common.separate.model.FenZhangMercSetModel;
import cn.scw.common.separate.model.MiniProgramModel;
import cn.scw.common.separate.model.RegisterModel;
import cn.scw.common.separate.model.base.BaseModel;
import cn.scw.common.separate.response.BaseResponse;
import cn.scw.common.separate.response.MiniProgramResponse;
import cn.scw.common.separate.utils.AESUtils;
import cn.scw.common.separate.utils.HttpClientUtils;
import cn.scw.common.separate.utils.MD5SignUtil;
import cn.scw.common.utils.DateUtils;
import cn.scw.common.utils.StringUtils;
import cn.scw.framework.config.RedisConfig;
import cn.scw.framework.redis.RedisCache;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.Map;

import static cn.scw.common.separate.common.Constants.*;

@Component
public class SeparateMethod {

    @Value("${separate.url}")
    private String separateUrl = "https://gate.jingweitech.cn";

    @Value("${separate.register}")
    private String register = "https://xiaochengxu.printeasy.top/prod-api/register";

    private final static String corgId = "TLWL";

    private final static String MercNo = "20111217500001";

    //默认分账商户号
    public final static String DEFAULT_MERCNO = "20120314130010";

    public  final static BigDecimal DEFAULT_BL = new BigDecimal(1);

    @Resource
    private RedisCache redisCache;

    /**
     * 加密并转化成Map
     *
     * @param object
     * @return
     */
    public Map<String, String> getMapToSign(Object object) {
        Map<String, String> map = JSONObject.parseObject(JSONObject.toJSONString(object), Map.class);
        map.put("mercNo", MercNo);
        map.put("dateTime", DateUtils.dateTimeNow());
        String sign = MD5SignUtil.sign(map, Constants.MD5_KEY);
        map.put("sign", sign);
        return map;
    }

    /**
     * 设置分账账号
     *
     * @param model
     * @return
     */
    public Boolean SetSeparateAccount(FenZhangMercSetModel model) {
        Map<String, String> map = getMapToSign(model);
        String body = HttpClientUtils.sendPostRequest(separateUrl + Constants.fenzhangMercSet, map, CHARAST, CHARAST);
        System.out.println("body=" + body);
        BaseResponse response = JSONObject.parseObject(body, BaseResponse.class);
        return response.getSuccess();
    }

    /**
     * 小程序支付下单
     *
     * @param miniProgramModel
     * @return
     */
    public MiniProgramResponse payMethod(MiniProgramModel miniProgramModel) {
        String body = post(miniProgramModel, miniProgramReq);
        System.out.println("body=" + body);
        JSONObject jsonObject = JSONObject.parseObject(body);
        MiniProgramResponse response = jsonObject.toJavaObject(MiniProgramResponse.class);
        response.setPackAge(jsonObject.getString("package"));
        return response;
    }

    /**
     * 小程序支付下单
     *
     * @param registerModel
     * @return
     */
    public BaseResponse registerAccount(RegisterModel registerModel) {
        registerModel.setRate("0.00800");
        registerModel.setIdentityNo(AESUtils.encrypt(registerModel.getIdentityNo(), AES_KEY));
        registerModel.setBankAccountName(AESUtils.encrypt(registerModel.getBankAccountName(), AES_KEY));
        registerModel.setStmManIdNo(AESUtils.encrypt(registerModel.getStmManIdNo(), AES_KEY));
        registerModel.setActNo(AESUtils.encrypt(registerModel.getActNo(), AES_KEY));
        registerModel.setMblNo(AESUtils.encrypt(registerModel.getMblNo(), AES_KEY));
        registerModel.setMerUrl(register);

        String body = post(registerModel, registerAccount);
        System.out.println("body=" + body);
        JSONObject jsonObject = JSONObject.parseObject(body);
        System.out.println(jsonObject.toJSONString());
        return jsonObject.toJavaObject(BaseResponse.class);
    }

    /**
     * @param lbnkProv
     * @param lbnkCity
     * @param bnkCd
     */
    public JSONArray getlbkNo(String lbnkProv, String lbnkCity, String bnkCd,String banktype) {
        BaseModel baseModel = new BaseModel();
        JSONObject object = JSONObject.parseObject(JSONObject.toJSONString(baseModel));
        object.put("banktype", banktype);
        object.put("lbnkProv", lbnkProv);
        object.put("lbnkCity", lbnkCity);
        object.put("bnkCd", bnkCd);
        String body = post(object, "/v1/merchant/lbnkNoGet");
        JSONObject response = JSONObject.parseObject(body);
        if ("0000".equals(response.getString("retCode"))) {
            return response.getJSONArray("data");
        }
        return null;
    }

    /**
     * 绑定小程序APPID
     *
     * @return
     */
    public Boolean bindAppId(String appId) {
        BindAppIdModel bindAppIdModel = new BindAppIdModel();
        String redisKey = MessageFormat.format(RedisConfig.TRANS_BIND_APPID, bindAppIdModel.getMercNo(), appId);
        Object value = redisCache.getCacheObject(redisKey);
        if (value == null) {
            bindAppIdModel.setSubAppid(appId);
            String body = post(bindAppIdModel, bindAppid);
            System.out.println("body=" + body);
            if (StringUtils.isBlank(body)) return false;
            BaseResponse response = JSONObject.parseObject(body, BaseResponse.class);
            if (response.getSuccess()) redisCache.setCacheObject(redisKey, true);
            return response.getSuccess();
        }

        return true;
    }


    public String updateFile(String filePath, String updateCode) {
        String reqUrl = separateUrl + "/v1/file/getUploadCode";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {

            HttpPost httppost = new HttpPost(reqUrl);

            FileBody bin = new FileBody(new File(filePath));
            //替换成自己的查corgId
            StringBody corgId = new StringBody(SeparateMethod.corgId, ContentType.TEXT_PLAIN);
            //新上传时不传，修改时填写需要修改的taskCode
            StringBody fileCode = new StringBody(updateCode, ContentType.TEXT_PLAIN);
            //请求ID
            StringBody reqId = new StringBody(DateUtils.dateTimeNow(), ContentType.TEXT_PLAIN);
            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    //.addPart("taskCode", taskCode)
                    .addPart("file", bin)
                    .addPart("corgId", corgId)
                    .addPart("fileCode", fileCode)
                    .addPart("reqId", reqId).build();
            httppost.setEntity(reqEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    String result = EntityUtils.toString(resEntity, "UTF-8");
                    System.out.println("请求返回信息：" + result);
                    JSONObject resultJson = JSONObject.parseObject(result);
                    if ("0000".equals(resultJson.getString("retCode"))) {
                        return resultJson.getString("fileCode");
                    }
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * post 提交
     *
     * @param object
     * @param url
     * @return
     */
    public String post(Object object, String url) {
        Map<String, String> map = getMapToSign(object);

        System.out.println("request params：" + JSONObject.toJSONString(map));

        return HttpClientUtils.sendPostRequest(separateUrl + url, map, CHARAST, CHARAST);
    }
}
